<template>
  <div class="city_main">
    <van-index-bar>
      <van-index-anchor index="定位城市" />
      <van-cell>
        <div class="city_button">
          <button @click="dingwei" class="first">{{ nowCity }}</button>
        </div>
      </van-cell>
      <van-index-anchor index="最近访问城市" />
      <van-cell>
        <div class="city_button">
          <button v-for="i in recentlyCity" :key="i">{{ i }}</button>
        </div>
      </van-cell>
      <van-index-anchor index="热门城市" />
      <van-cell>
        <div class="city_button">
          <button v-for="i in hotCity" :key="i.id" @click="checkCity(i.nm)">
            {{ i.nm }}
          </button>
        </div>
      </van-cell>
      <div v-for="(item, index) in city" :key="index + 1">
        <van-index-anchor :key="index" :index="item.initial" />
        <van-cell
          v-for="(i, key) in item.list"
          :key="index + '-' + key"
          :title="i.name"
          @click="checkCity(i.name)"
        />
      </div>
    </van-index-bar>
  </div>
</template>
<script>
import axios from "axios";
import city from "../assets/json/city.json";

export default {
  name: "City",
  data() {
    return {
      city: [],
      hotCity: [],
      nowCity: "定位",
      default: "深圳",
      recentlyCity: [],
    };
  },
  created() {
    this.city = city.city;

    //获得最近访问的城市数据
    this.recentlyCity = sessionStorage.getItem("recentlyCity");
    if(!this.recentlyCity){
      //没有值则赋予空值
      this.recentlyCity = new Set();
    }else{
      //解析
      this.recentlyCity = new Set(this.recentlyCity.replace(/[\[\]\"]/g, "").split(","));
    }
    
    if (sessionStorage.getItem("city")) {
      this.hotCity = sessionStorage.getItem("city");
      try {
        this.hotCity = JSON.parse(this.hotCity);
        if (this.hotCity instanceof Array) {
          console.log("City1:", this.hotCity);
          return;
        }
      } catch (e) {
        console.log("异常", e);
      }
    }
    axios
      .get("api/dianying/cities.json")
      .then((data) => {
        this.hotCity = data.data.cts.slice(0, 11);
        sessionStorage.setItem("city", JSON.stringify(this.hotCity));
        console.log("City2:", this.hotCity);
      })
      .catch((error) => {
        console.log("异常", error);
      });
  },
  methods: {
    dingwei() {
      //定位
      this.nowCity = "定位中...";
      if (window.navigator.geolocation) {
        window.navigator.geolocation.getCurrentPosition(
          (position) => {
            let latitude = position.coords.latitude; //维度
            let longitude = position.coords.longitude; //经度
            axios
              .get(
                `geocoder?location=${longitude},${latitude}&output=json&key=HQf6Q62QiXxoz9wMIG9inx0nDKP21Uq8`
              )
              .then((data) => {
                this.nowCity = data.data.result.addressComponent.city;
                if (this.nowCity == "") {
                  this.nowCity = "定位失败，请稍后再试";
                }
              })
              .catch((error) => {
                console.log("异常:", error);
                this.nowCity = "定位失败，请稍后再试";
              });
          },
          (error) => {
            console.log("获取失败", error);
            this.nowCity = "定位失败，请稍后再试";
          },
          {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0,
          }
        );
      } else {
        alert("您的浏览器不支持定位");
        this.nowCity = "定位失败，请稍后再试";
      }
    },
    checkCity(name) {
      //点击城市
      this.recentlyCity.add(name);
      sessionStorage.setItem(
        "recentlyCity",
        "[" + [...this.recentlyCity] + "]"
      );

      //跳转
      this.$router.push({
          name:"Hot",
          params:{
              "city":name
          }
      })
    },
  },
};
</script>

<style scoped>
.city_main .city_button {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.city_main .container {
  width: 300px;
  height: 300px;
}



.city_main .city_button button {
  width: 30%;
  height: 0.933333rem;
  margin-left: 2.5%;
  margin-top: 0.266667rem;
  background-color: white;
  border: 1px solid rgb(219, 219, 219);
  border-radius: 0.08rem;
}

.city_main .city_button .first{
    width: 50%;
    white-space: nowrap;
}
</style>